package com.l024.meet.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.l024.framework.bmob.BmobManager;
import com.l024.framework.bmob.IMUser;
import com.l024.framework.bmob.MyDate;
import com.l024.framework.entity.Constants;
import com.l024.framework.manager.DialogManager;
import com.l024.framework.utils.Logutils;
import com.l024.framework.utils.SpUtils;
import com.l024.framework.view.DialogView;
import com.l024.framework.view.TouchPictureView;
import com.l024.meet.MainActivity;
import com.l024.meet.R;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * 登录页
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    /**
     * 1.点击发送按钮，发送验证码。弹出验证框。通过发送验证码
     * 2.发送验证码。按钮不可点击。按钮倒计时。倒计时结束。按钮可点击。文字变发送
     * 3.通过手机号和验证码桐庐
     * 4.登录成功后保存用户对象
     */
    //手机号
    private EditText etPhone;
    //填写code
    private EditText etCode;
    //发送验证码
    private Button btnSendCode;
    //登录按钮
    private Button btnLogin;
    //测试登录
    private TextView tvTestLogin;
    //用户协议
    private TextView tvUserAgreement;

    private static final int H_TIME = 1001;
    //倒计时
    private static int TIME = 60;

    private DialogView mCodeDialogView;
    private TouchPictureView touchPictureView;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case H_TIME:{
                    TIME--;
                    btnSendCode.setText(TIME+"s");
                    if(TIME>0){
                        mHandler.sendEmptyMessageDelayed(H_TIME,1000);
                    }else{
                        btnSendCode.setEnabled(true);
                        btnSendCode.setText(getString(R.string.text_login_send));
                    }
                    break;
                }
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {
        etPhone = (EditText) findViewById(R.id.et_phone);
        etCode = (EditText) findViewById(R.id.et_code);
        btnSendCode = (Button) findViewById(R.id.btn_send_code);
        btnLogin = (Button) findViewById(R.id.btn_login);
        tvTestLogin = (TextView) findViewById(R.id.tv_test_login);
        tvUserAgreement = (TextView) findViewById(R.id.tv_user_agreement);
        btnSendCode.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        tvTestLogin.setOnClickListener(this);
        String phone = SpUtils.getInstance().getString(Constants.SP_PHONE, "");
        if(!TextUtils.isEmpty(phone)){
            etPhone.setText(phone);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //测试
            case R.id.tv_test_login:{
                testLogin();
                break;
            }
            case R.id.btn_send_code:{
                //初始化验证码弹框
                initDialogView();
                DialogManager.getInstance().show(mCodeDialogView);
                break;
            }
            case R.id.btn_login:{
                login();
                break;
            }
        }
    }

    /**
     * 获取验证码
     */
    private void sendSMS(){
        String phone = etPhone.getText().toString().trim();
        if(TextUtils.isEmpty(phone)){
            Toast.makeText(this, getString(R.string.text_login_phone_null), Toast.LENGTH_SHORT).show();
        }else{
            BmobManager.getInstance().requestSMSCode(phone, new QueryListener<Integer>() {
                @Override
                public void done(Integer smsId, BmobException e) {
                    if (e == null) {
                        btnSendCode.setEnabled(false);
                        mHandler.sendEmptyMessage(H_TIME);
//                        Toast.makeText(LoginActivity.this, "发送验证码成功，短信ID：" + smsId, Toast.LENGTH_SHORT).show();
                        Logutils.i("发送验证码成功，短信ID：" + smsId);
                    } else {
                        Logutils.e("发送验证码失败：" + e.getErrorCode() + "-" + e.getMessage());
                    }
                }
            });
        }
    }

    /**
     * 登录
     */
    private void login(){
        String phone = etPhone.getText().toString().trim();
        String code = etCode.getText().toString().trim();
        if(TextUtils.isEmpty(phone)){
            Toast.makeText(this, getString(R.string.text_login_phone_null), Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(code)){
            Toast.makeText(this, getString(R.string.text_login_code_null), Toast.LENGTH_SHORT).show();
            return;
        }
        BmobManager.getInstance().signOrLoginByMobilePhone(phone, code, new LogInListener<BmobUser>() {
            @Override
            public void done(BmobUser bmobUser, BmobException e) {
                if (e == null) {
                    Toast.makeText(LoginActivity.this, "短信注册或登录成功：" + bmobUser.getUsername(), Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    //保存手机号
                    SpUtils.getInstance().putString(Constants.SP_PHONE,phone);
                    finish();
                } else {
                    System.out.println("登录message:---->"+e.getMessage());
                    Toast.makeText(LoginActivity.this, "短信注册或登录失败：" + e.getErrorCode() + "-" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 弹出验证
     */
    private void initDialogView(){
        mCodeDialogView = DialogManager.getInstance().initView(this, R.layout.dialog_code_view);
        touchPictureView = mCodeDialogView.findViewById(R.id.touch_picture_view);
        touchPictureView.setOnViewResultListener(new TouchPictureView.OnViewResultListener() {
            @Override
            public void onResult(boolean isSuccess) {
                if(isSuccess){
                    DialogManager.getInstance().hide(mCodeDialogView);
                    sendSMS();
                }else{
                    Toast.makeText(LoginActivity.this, "验证失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initUser(){
        IMUser user = new IMUser();

        user.setTokenNickName("爱哭的毛毛虫");
        user.setTokenPhoto("http://file.l024.xin/2020/03/06/5dfb6f9732fd4b37a9d02bd065a9506d.jpg");

        user.setUsername("15528950203");
        user.setPassword("123456");

        user.setNickName("http://file.l024.xin/2020/03/06/5dfb6f9732fd4b37a9d02bd065a9506d.jpg");
        user.setPhoto("http://file.l024.xin/2020/03/06/5dfb6f9732fd4b37a9d02bd065a9506d.jpg");
        user.setSex(false);
        user.setDesc("模拟登录用户");

        user.setMobilePhoneNumber("15528950203");
        user.setMobilePhoneNumberVerified(true);

        user.setAge(20);
        user.setBitrhDay("2020-12-02");
        user.setConstellation("射手座");
        user.setHobby("打游戏");
        user.setStatus("单身");

        user.signUp(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e != null) {
                    Logutils.e("Error:" + e.toString());
                }
            }
        });
    }

    //测试登录
    private void testLogin(){
//        initUser();
        String phone = etPhone.getText().toString().trim();
        String pwd = etCode.getText().toString().trim();
        if(TextUtils.isEmpty(phone)){
            Toast.makeText(this, getString(R.string.text_login_phone_null), Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(pwd)){
            Toast.makeText(this, getString(R.string.text_login_code_null), Toast.LENGTH_SHORT).show();
            return;
        }
        BmobManager.getInstance().loginByPhone(phone, pwd, new LogInListener<BmobUser>() {
            @Override
            public void done(BmobUser bmobUser, BmobException e) {
                if(bmobUser!=null){
                    if (e == null) {
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        //保存手机号
                        SpUtils.getInstance().putString(Constants.SP_PHONE,phone);
                        finish();
                    } else {
                        Logutils.e("登录失败"+ e.getErrorCode() + "-" + e.getMessage() );
                    }
                }else{
                    Logutils.e("登录失败");
                }
            }
        });

//        MyDate myDate = new MyDate();
//        myDate.setName("张三");
//        myDate.setSex(0);
//        myDate.save(new SaveListener<String>() {
//            @Override
//            public void done(String s, BmobException e) {
//                if(e!=null){
//                    Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
//                }else{
//                    Toast.makeText(LoginActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
    }

}
